package com.sjr.easy.chat.app.controller;

import com.sjr.easy.chat.app.EasyChatAppConfig;
import com.sjr.easy.chat.app.constants.UserHeadPortraitStoreTypeEnum;
import com.sjr.easy.chat.model.User;
import com.sjr.easy.chat.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@Slf4j
@Controller
@Api("App用户相关接口-非Rest")
public class AppUserControllerNoRest {

    @Autowired
    private UserService userService;

    @Autowired
    private EasyChatAppConfig easyChatAppConfig;

    @ApiOperation("用户头像图片查询")
    @GetMapping("/app/user/getUserHeadPortrait")
    public void getUserHeadPortrait(@RequestParam("code") String code, HttpServletResponse response) {
        User user = userService.selectByCode(code);
        if (user == null) {
            return;
        }
        if (UserHeadPortraitStoreTypeEnum.local.getCode().equals(user.getHeadPortraitStoreType())) {
            // 文件存储目录
            String baseFilePath = easyChatAppConfig.getUserHeadPortraitStorePath();
            if (!baseFilePath.endsWith("/")) {
                baseFilePath += "/";
            }
            String filePath = baseFilePath + user.getHeadPortrait();
            File imageFile = new File(filePath);
            if (imageFile.exists()) {
                String contentType = "";
                try (
                        ServletOutputStream outputStream = response.getOutputStream()
                ) {
                    contentType = Files.probeContentType(Paths.get(filePath));
                    if (StringUtils.isNotEmpty(contentType)) {
                        response.setContentType(contentType);
                    }
                    byte[] imageBytes = FileUtils.readFileToByteArray(imageFile);

                    IOUtils.write(imageBytes, outputStream);
                    outputStream.flush();
                } catch (IOException e) {
                    log.error("e:", e);
                }
            }
        }
    }

}
